package com.swust.listview;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class MineListViewAdapter extends BaseAdapter {
    private final AppCompatActivity context;
    private final List<Integer> objects;
    private int prePosition = 0;
    private List<TextView> caches = new ArrayList<>();

    public MineListViewAdapter(AppCompatActivity context, List<Integer> sourceList) {
        this.context = context;
        this.objects = sourceList;
        for (int i = 0; i < sourceList.size(); i++) {
            caches.add(null);
        }
    }

    @Override
    public int getCount() {
        return objects.size();
    }

    @Override
    public Object getItem(int position) {
        return objects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_item_mine_list_view, null);
        TextView textView = view.findViewById(R.id.textview);
        textView.setText(String.valueOf(objects.get(position)));
        return view;
    }

    public void setPrePosition(View view, int position) {
        //上一个节点的样式变更
        TextView preTV = caches.get(prePosition);
        if (preTV != null) {
            preTV.setBackgroundColor(context.getColor(R.color.white));
            preTV.setTextColor(context.getColor(R.color.black));
        }

        TextView curTV;
        if (view == null) {
            curTV = caches.get(0);
        } else {
            curTV = view.findViewById(R.id.textview);
        }
        if (curTV != null) {
            curTV.setBackgroundColor(context.getColor(R.color.orange));
            curTV.setTextColor(context.getColor(R.color.white));
            caches.set(position, curTV);
        }

        //设置上一个节点下标为当前节点下标
        this.prePosition = position;
        notifyDataSetChanged();
    }
}
